package com.lianbang.pharmacy.module.user

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import cn.ubest.mvvmcore.base.BaseActivity
import cn.ubest.mvvmcore.utils.*
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.lianbang.pharmacy.R
import com.lianbang.pharmacy.bean.AddressListBean
import com.lianbang.pharmacy.bean.AreaBean
import com.lianbang.pharmacy.databinding.ActivityEditAddressBinding
import com.lianbang.pharmacy.vm.AddressVM
import kotlinx.android.synthetic.main.activity_edit_address.*
import java.util.*

/**
 * Created by maoqi on 2020/12/16.
 */
class EditAddressActivity : BaseActivity<AddressVM, ActivityEditAddressBinding>() {

    private val mAddress by lazy {
        intent.getParcelableExtra<AddressListBean?>("address")
            ?: AddressListBean(
                null,
                "",
                "",
                "",
                "",
                "",
                "",
                null,
                0
            )
    }


    companion object {
        const val REQ_CODE = 1002
        fun start(context: Activity?, address: AddressListBean?) {
            context?.also {
                val starter = Intent(it, EditAddressActivity::class.java)
                starter.putExtra("address", address)
                it.startActivityForResult(starter, REQ_CODE)
            }

        }
    }

    override fun initLayout(): Int {
        return R.layout.activity_edit_address
    }

    override fun initData(intent: Intent) {
        mViewModel.mAddressLiveData.observe(this, androidx.lifecycle.Observer {
            if (it is Boolean && it) {
                setResult(Activity.RESULT_OK)
                finish()
            }
        })
        val assetsString = ResourcesUtils.getAssetsString(this, "area.json")
        options1Items = JsonUtils.jsonToList(assetsString, AreaBean::class.java)
        for (i in 0 until options1Items.size) {
            val cityList = ArrayList<String>()
            val provinceAreaList = ArrayList<ArrayList<String>>()
            for (c in 0 until options1Items[i].city.size) {
                val cityName: String = options1Items[i].city[c].name
                cityList.add(cityName) //添加城市
                val cityAreaList =
                    ArrayList<String>()
                cityAreaList.addAll(options1Items[i].city[c].area)
                provinceAreaList.add(cityAreaList)
            }
            options2Items.add(cityList)
            options3Items.add(provinceAreaList)
        }
    }

    override fun initView() {
        mBinding.address = mAddress
        sc_switch.setOnCheckedChangeListener { buttonView, isChecked ->
            mAddress.is_default = if (isChecked) 1 else 0
        }
        sc_switch.isChecked = mAddress.is_default == 1

        if (mAddress.province.isNotEmpty() && mAddress.city.isNotEmpty() && mAddress.district.isNotEmpty()) {
            btn_choose_address.text = "${mAddress.province} ${mAddress.city} ${mAddress.district}"
        }
        btn_choose_address.setOnClickListener(object : DoubleClickHelper.OnClickListener() {
            override fun onClicked(view: View?) {
                KeyboardUtils.hideSoftInput(this@EditAddressActivity)
                showSelectAreaDialog()
            }

        })
    }

    override fun loadData() {

    }

    override fun setToolbarTitle(): String? {
        return "编辑地址"
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_edit_address, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.btn_save -> saveAddress()
        }
        return super.onOptionsItemSelected(item)
    }

    private fun saveAddress() {
        if (mAddress.real_name.isEmpty()) {
            ToastUtils.toast("请输入姓名")
            return
        }
        if (mAddress.phone.isEmpty()) {
            ToastUtils.toast("请输入手机号")
            return
        }
        if (mAddress.province.isEmpty()
            || mAddress.city.isEmpty()
            || mAddress.district.isEmpty()
        ) {
            ToastUtils.toast("请选择地区")
            return
        }
        if (mAddress.detail.isEmpty()) {
            ToastUtils.toast("请输入详细地址")
            return
        }
        mViewModel.addOrChangeAddress(mAddress)
    }


    private var options1Items = mutableListOf<AreaBean>()
    private val options2Items = mutableListOf<List<String>>()
    private val options3Items = mutableListOf<List<List<String>>>()

    private var mAreaSelector: OptionsPickerView<in Any>? = null

    /**
     * 地区选择器
     */
    private fun showSelectAreaDialog() {
        if (mAreaSelector == null) {
            mAreaSelector = OptionsPickerBuilder(this,
                OnOptionsSelectListener { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
                    val province =
                        if (options1Items.isNotEmpty()) options1Items[options1].name else ""

                    val city = if (options2Items.size > 0
                        && options2Items[options1].isNotEmpty()
                    ) {
                        options2Items[options1][options2]
                    } else ""

                    val district = if (options2Items.isNotEmpty()
                        && options3Items[options1].isNotEmpty()
                        && options3Items[options1][options2].isNotEmpty()
                    ) {
                        options3Items[options1][options2][options3]
                    } else ""

                    mAddress.province = province
                    mAddress.city = city
                    mAddress.district = district
                    btn_choose_address.text = "$province $city $district"
                })
                .setTitleText("选择地区")
//                    .setContentTextSize(20)//设置滚轮文字大小
//                    .setDividerColor(Color.LTGRAY)//设置分割线的颜色
//                    .setSelectOptions(0, 0,0)//默认选中项
//                    .setBgColor(Color.BLACK)
//                    .setTitleBgColor(Color.DKGRAY)
//                    .setTitleColor(Color.LTGRAY)
//                    .setCancelColor(Color.YELLOW)
//                    .setSubmitColor(Color.YELLOW)
//                    .setTextColorCenter(Color.LTGRAY)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
//                    .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                    .setLabels("省", "市", "区")
//                    .setOutSideColor(0x00000000) //设置外部遮罩颜色
//                    .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
//                        @Override
//                        public void onOptionsSelectChanged(int options1, int options2, int options3) {
//
//                        }
//                    })
                .build()

            mAreaSelector?.setPicker(options1Items, options2Items, options3Items)
        }
        mAreaSelector?.show()
    }

}